package com.wash.shoes.controller.pc;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.entity.AccessoriesPo;
import com.wash.shoes.entity.FactoryshelvesRackGridPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.entity.SimpleCustomPhone;
import com.wash.shoes.mapper.AccessoriesMapper;
import com.wash.shoes.mapper.OrderMapper;
import com.wash.shoes.request.FactoryShelvesGridQueryRequest;
import com.wash.shoes.request.ForceReleasesGridRequest;
import com.wash.shoes.service.FactoryShelvesService;
import com.wash.shoes.service.FactoryshelvesRackGridService;
import com.wash.shoes.service.OrderTransportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@Api(tags = {"工厂货架格子"})
@RestController
@RequestMapping("/factoryShelvesGrid")
@Slf4j
public class FactoryShelvesGridController {
    @Autowired
    private FactoryshelvesRackGridService factoryshelvesRackGridService;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    OrderTransportService orderTransportService;

    @ApiOperation("获取工厂货架格子列表")
    @GetMapping("/list")
    public R getFactoryShelvesGridList(@Valid FactoryShelvesGridQueryRequest queryRequest) {
        StopWatch sw = new StopWatch();
        sw.start("queryListparam");
        Page<FactoryshelvesRackGridPo> data = factoryshelvesRackGridService.queryListByParam(queryRequest.toPage(), queryRequest.getId(),
                queryRequest.getOrderNo(), queryRequest.getPhone(), queryRequest.getLastNum());
        sw.stop();
        /*     factoryshelvesRackGridService.list(new LambdaQueryWrapper<FactoryshelvesRackGridPo>()
                .eq(FactoryshelvesRackGridPo::getFactoryshelves_id, queryRequest.getId())
                .eq(FactoryshelvesRackGridPo::getStatus, FactoryShelvesStatusEnum.ONLINE)
                .orderByAsc(FactoryshelvesRackGridPo::getSortNum));*/
        sw.start("queryList");
/*        List<List<FactoryshelvesRackGridPo>> data1 =CollectionUtil.split(data,10);
        List<FactoryshelvesRackGridPo> finalData = Lists.newArrayList(data);*/
        Set<String> orderIds = new HashSet<>();
        data.getRecords().forEach(e -> {
            if (StringUtils.isNotEmpty(e.getOrderId())) {
                orderIds.add(e.getOrderId());
            }
        });
        Map<String, SimpleCustomPhone> phoneMap = Maps.newHashMap();
        if (CollectionUtil.isNotEmpty(orderIds)) {
            //获取订单信息
            /**/
            List<SimpleCustomPhone> orderPos = orderMapper.getCustomPhone(orderIds);

            orderPos.stream().forEach(e -> {
                phoneMap.put(e.getId(), e);
            });
        }


        for (FactoryshelvesRackGridPo e : data.getRecords()) {
            // 判断是否有订单id
            if (StringUtils.isNotEmpty(e.getOrderId())) {
                // 获取订单信息
                FactoryshelvesRackGridPo.CustomInfo customInfo = new FactoryshelvesRackGridPo.CustomInfo();
                SimpleCustomPhone simpleCustomPhone = phoneMap.get(e.getOrderId());
                if (Objects.isNull(simpleCustomPhone)) {
                    continue;
                }

                //抖音用户落入到客户表姓名 电话号码有问题，修改了在用这个方式设置
                //现在用户以及电话暂时查物流表
                OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderNoType(simpleCustomPhone.getOrderNo(), "取鞋");
                customInfo.setOrderNo(simpleCustomPhone.getOrderNo());
                if (Objects.nonNull(orderTransportPo)) {
                    customInfo.setPhone(orderTransportPo.getSendMobile());
                    customInfo.setName(orderTransportPo.getSendName());
                } else {
                    customInfo.setPhone(simpleCustomPhone.getCustomPhone());
                    customInfo.setName(simpleCustomPhone.getName());
                }
                Map<String, Object> map = Maps.newHashMap();
                // 这里需要取实际订单的数据 TODO jjz
                map.put("lable", "衣鞋总数量");
                map.put("count", simpleCustomPhone.getShoeCount());
                //根据orderid获取配饰数量
                long accessoriesCount = accessoriesMapper.selectCount(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, e.getOrderId()));

                Map<String, Object> accessoriesMap = Maps.newHashMap();
                // 放配饰数量
                accessoriesMap.put("lable", "配饰数量");
                accessoriesMap.put("count", accessoriesCount);

                List list = Lists.newArrayList(map, accessoriesMap);
                customInfo.setData(list);
                // 设置这个格子的客服数据
                e.setCustomInfo(customInfo);
            }
        }
        sw.stop();
        log.info("耗时:{}", sw.prettyPrint());
        return R.ok(data);
    }

    @Autowired
    private AccessoriesMapper accessoriesMapper;

    @ApiOperation("获取工厂货架格子详情")
    @GetMapping("/detail")
    public R getDetailById() {
        return R.ok();
    }

    @ApiOperation("强制释放格子绑定的订单")
    @PostMapping("/releasesGrid")
    public R releasesGrid(@RequestBody @Valid ForceReleasesGridRequest forceReleasesGridRequest) {

        FactoryshelvesRackGridPo factoryshelvesRackGridPo = factoryshelvesRackGridService.getById(forceReleasesGridRequest.getId());
        Assert.notNull(factoryshelvesRackGridPo, "格子不存在.id:" + forceReleasesGridRequest.getId());
        log.info("强制释放格子绑定的订单,订单id:{},格子id:{},格子编号:{}", factoryshelvesRackGridPo.getOrderId(), forceReleasesGridRequest.getId(), factoryshelvesRackGridPo.getShowCode());
        boolean flag = updateFactoryShevelsOrderId(factoryshelvesRackGridPo);
        // 修改货架的已使用数量
        return R.ok(flag && SqlHelper.retBool(factoryShelvesService.updateUseNumInteger(factoryshelvesRackGridPo.getFactoryshelvesId())));
    }

    @Autowired
    private FactoryShelvesService factoryShelvesService;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean updateFactoryShevelsOrderId(FactoryshelvesRackGridPo factoryshelvesRackGridPo) {
        String orderId = factoryshelvesRackGridPo.getOrderId();
        factoryshelvesRackGridPo.setOrderId(null);
        int falg = factoryshelvesRackGridService.updateFactoryShevelsOrderIdWithId(factoryshelvesRackGridPo.getId());
        log.info("释放货架绑定的订单:{},falg:{},orderId:{}", factoryshelvesRackGridPo.getFactoryshelvesId(), falg, orderId);
        return SqlHelper.retBool(falg);
    }
}
